// Language switching utility for the platform

class LanguageUtil {
  constructor() {
    this.supportedLanguages = ['en', 'zh'];
    this.defaultLanguage = 'zh'; // Default to Chinese as per project requirements
  }

  /**
   * Gets the current language from localStorage or browser settings
   */
  getCurrentLanguage() {
    // First check localStorage for user preference
    const storedLang = localStorage.getItem('preferred_language');
    if (storedLang && this.supportedLanguages.includes(storedLang)) {
      return storedLang;
    }

    // Then check browser language
    const browserLang = navigator.language.split('-')[0]; // Extract language code (e.g., 'en' from 'en-US')
    if (this.supportedLanguages.includes(browserLang)) {
      return browserLang;
    }

    // Default to 'en' if browser language not supported
    return this.defaultLanguage;
  }

  /**
   * Sets the preferred language and stores it in localStorage
   */
  setLanguage(lang) {
    if (!this.supportedLanguages.includes(lang)) {
      console.warn(`Language "${lang}" is not supported. Using default language.`);
      lang = this.defaultLanguage;
    }

    localStorage.setItem('preferred_language', lang);
    // Trigger language change event for components to react
    window.dispatchEvent(new Event('languageChanged'));
  }

  /**
   * Gets the direction of the current language (ltr or rtl)
   * (Currently all supported languages are left-to-right, but this could be extended)
   */
  getLanguageDirection() {
    const currentLang = this.getCurrentLanguage();
    // Add RTL languages here when needed
    return 'ltr'; // Left-to-right by default
  }

  /**
   * Gets the language name for display
   */
  getLanguageDisplayName(lang) {
    const languageNames = {
      'en': 'English',
      'zh': '中文'
    };
    return languageNames[lang] || lang;
  }
}

export default new LanguageUtil();